﻿using System;
using System.Data;
using NHibernate.SqlTypes;
using NHibernate.UserTypes;

namespace EfficientlyLazy.PhotoFramer.UserTypes
{
    public class Encrypted<T> : IUserType
    {
        public new bool Equals(object x, object y)
        {
            return object.Equals(x, y);
        }

        public int GetHashCode(object x)
        {
            return x.GetHashCode();
        }

        public object NullSafeGet(IDataReader rs, string[] names, object owner)
        {
            var r = rs[names[0]];

            if (r == DBNull.Value || r == null)
            {
                return default(T);
            }

            //string data = _encryption.Decrypt(r.ToString());
            var data = r.ToString();

            return Convert.ChangeType(data, typeof(T));
        }

        public void NullSafeSet(IDbCommand cmd, object value, int index)
        {
            //object paramVal = value == null ? _encryption.Encrypt(string.Empty) : _encryption.Encrypt(value.ToString());
            object paramVal = value == null ? string.Empty : value.ToString();

            IDataParameter parameter = (IDataParameter)cmd.Parameters[index];
            parameter.Value = paramVal;
        }

        public object DeepCopy(object value)
        {
            return value;
        }

        public object Replace(object original, object target, object owner)
        {
            return original;
        }

        public object Assemble(object cached, object owner)
        {
            return cached;
        }

        public object Disassemble(object value)
        {
            return value;
        }

        public SqlType[] SqlTypes
        {
            get { return new SqlType[] { new StringSqlType() }; }
        }

        public Type ReturnedType
        {
            get { return typeof(T); }
        }

        public bool IsMutable
        {
            get { return false; }
        }
    }
}